<template>
  <div class="cockpit">
    <!-- 右侧搜索工具面板 -->
    <div
      class="right-search"
      v-show="showSearchPanel"
      v-loading="isRightSearchLoading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <el-tabs v-model="rightTabActiveName">
        <el-tab-pane label="地名地址" name="address">
          <div class="search-bar">
            <el-input
              class="searchInput"
              placeholder="请输入关键词"
              size="small"
              v-model="addressSearchKeyword"
              clearable
              @keydown.enter.native="onAddressKeyDown"
            />
          </div>

          <div class="search-result">
            <el-scrollbar>
              <div
                v-for="item in addressSearchResult"
                class="search-result-item"
                :key="item.id"
                @click="onAddressSearchResultClick(item)"
              >
                <span class="name">{{ item.name }}</span>
                <!-- 地名地址查询未返回地址，暂时隐藏 -->
                <!--                <div class="address">-->
                <!--                  <el-image-->
                <!--                    class="img"-->
                <!--                    :src="-->
                <!--                      require('@/assets/img/location.png')-->
                <!--                    "-->
                <!--                  />-->
                <!--                  <span class="label">{{-->
                <!--                    item.address-->
                <!--                  }}</span>-->
                <!--                </div>-->
              </div>
            </el-scrollbar>
          </div>
        </el-tab-pane>

        <el-tab-pane label="要素查询" name="feature">
          <div class="search-bar">
            <el-select
              :popper-append-to-body="false"
              class="search-layer"
              v-model="featureSearchLayer"
              filterable
              placeholder="请选择"
              size="small"
              @visible-change="
                onFeatureLayerSelectVisibleChange
              "
            >
              <el-option
                v-for="item in featureSearchLayerOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>

            <el-input
              class="search-input"
              placeholder="请输入关键词"
              size="small"
              v-model="featureSearchKeyword"
              clearable
              @keydown.enter.native="onFeatureKeyDown"
            />
          </div>

          <div class="search-result">
            <el-scrollbar>
              <div
                v-for="(item, index) in featureSearchResult"
                class="search-result-item"
                :key="item.dataServicePkid + '-' + index"
                @click="onFeatureSearchResultClick(item)"
              >
                <span class="name"
                  >SmID: {{ item.SmID }}</span
                >
                <span class="name"
                  >{{ item.resultKey }}:
                  {{ item.resultValue }}</span
                >
              </div>
            </el-scrollbar>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 底部底图影像、数据名称切换面板 -->
    <div
      :class="['bottom-tab-box', isShrink ? 'shrink' : '']"
      :style="
        !isShrink && allDataList.length > 4
          ? 'height: 265px;overflow-y: auto'
          : ''
      "
      v-show="mapServices.length > 1 || allDataList.length"
    >
      <el-scrollbar>
        <div class="bottom-tab">
          <div
            class="right-service__wrapper"
            v-show="mapServices.length > 1"
          >
            <div @click="mapOpenFun">
              <el-input
                placeholder="底图影像"
                disabled
                style="width: 110px; margin-right: 26px"
                v-show="mapServices.length > 1"
              >
              </el-input>
            </div>

            <!-- 底图影像切换 -->
            <div
              class="right-service"
              v-show="mapServices.length > 1"
            >
              <span
                class="left-right"
                @click="leftShow"
                v-show="
                  mapServices.length > 4 && groupIndex !== 1
                "
                >&lt;</span
              >
              <div
                class="service-item"
                :class="
                  activeService.pkid === item.pkid
                    ? 'active-item'
                    : ''
                "
                v-for="item in showServiceList"
                :key="item.pkid"
                @click="showService(item)"
              >
                <span>{{ item.serviceName }}</span>
              </div>
              <span
                class="left-right"
                @click="rightShow"
                v-show="
                  mapServices.length > 4 &&
                  groupIndex * 4 < mapServices.length
                "
                >&gt;</span
              >
            </div>
          </div>
          <div
            class="right-service__wrapper"
            v-for="(value, index) in allDataList"
            :key="index"
          >
            <div @click="openFun(index)">
              <el-input
                :placeholder="value.name"
                disabled
                style="width: 110px; margin-right: 26px"
              >
              </el-input>
            </div>
            <!-- 数据名称切换 -->
            <div class="right-service">
              <span
                class="left-right"
                @click="dataListLeftShow(value)"
                v-show="
                  value.dataList.length > 4 &&
                  value.currentPage !== 1
                "
                >&lt;</span
              >
              <div
                class="service-item"
                v-for="(item, index2) in value.showDataList"
                :key="item.pkid"
                :class="{
                  'active-item':
                    item.pkid ===
                    value.dataList[value.currentIndex].pkid
                }"
                :disable="!item.serviceUrl"
                @click="
                  dataClickHandle(item, index, index2)
                "
              >
                {{ item.serviceName }}
              </div>
              <span
                class="left-right"
                @click="dataListRightShow(value)"
                v-show="
                  value.dataList.length > 4 &&
                  value.dataList.length >
                    value.currentPage * 4
                "
                >&gt;</span
              >
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>

    <router-view />
    <div class="right">
      <Utool
        @changeTool="changeTool"
        :viewerId="defaultViewId"
        :topic="activeMenu.type"
        :legend-data="legendData"
      />
    </div>
    <div
      style="
        height: 95px;
        width: 1074px;
        margin-left: calc(50% - 537px);
      "
      @mouseover="topShow"
    >
      <img
        class="cockpit-menu-background"
        :src="BackgroundCockpitMenu"
        alt="background"
        v-show="topMenuShow"
      />
      <div class="cockpit-menu flex-x" v-show="topMenuShow">
        <div
          class="cockpit-menu-item flex-x cross-center"
          :class="{ active: $route.path === item.path }"
          v-for="(item, index) in menus"
          :key="index"
          @click="handleMenuItemClick(index)"
          @mouseover="doBlueShow(index)"
          @mouseleave="doBlueHide(index)"
        >
          <Icon
            :title="item.title"
            :name="item.icon"
            font-size="20"
          />
          <span class="title">{{ item.title }}</span>
          <span
            class="separator"
            v-if="index !== menus.length - 1"
            >/</span
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import BackgroundCockpitMenu from '@/assets/img/background-cockpit-menu.png'
import Icon from '@/components/icon'
import Utool from '@/components/utool'
import axios from 'axios'
import { getAction } from '@/utils/helper'
import { globalBaseMap } from '@/utils/basemap'
import { topicDefaultList } from '@/api/tree'
import New from '@/utils/new'
import { checkMenuById } from '@/utils/menu/menu'
import { ADDRESS_QUERY_URL } from '@/api/config.js'

const mapViewer = {}
let _layerManager = null
let previousGeojsonList = []
let previousEntity

export default {
  // inject: ['viewerId'],
  name: 'Cockpit',
  components: {
    Icon,
    Utool
  },
  data() {
    return {
      BackgroundCockpitMenu,
      navList: [
        {
          title: '搜索',
          icon: 'sousuo',
          path: 'search',
          id: ''
        },
        {
          title: '现状',
          icon: 'xianzhuang',
          path: '/cockpit/now',
          id: 411
        },
        {
          title: '规划',
          icon: 'guihua',
          path: '/cockpit/plan',
          id: 412
        },
        {
          title: 'BIM',
          icon: 'bim',
          path: '/cockpit/bim',
          id: 413
        },
        {
          title: '项目',
          icon: 'xiangmu',
          path: '/cockpit/proj',
          id: 414
        }
      ],
      isShrink: true, // 是否收缩tab
      oldDataIndex: -1, // 切换时调整到最后的index
      showSearchPanel: false,
      rightTabActiveName: 'address',
      // 查询出来的所有地名地址数据
      allAddressData: [],
      addressSearchKeyword: '',
      addressSearchResult: [],
      featureSearchLayerOptions: [],
      featureSearchLayer: '',
      featureSearchKeyword: '',
      featureSearchResult: [],
      mapServices: [],
      activeService: {},
      dataChangePkid: '',
      show: false,
      // maxBimData: 0,
      layerList: [],
      groupIndex: 1,
      dataListGroupIndex: 1,
      showServiceList: [],
      showDataList: [],
      menus: [
        {
          icon: 'chengshiquanjing',
          title: '城市全景',
          path: '/cockpit/panorama',
          type: 'chengshiquanjing',
          id: '411'
        },
        {
          icon: 'weilailantu',
          title: '未来蓝图',
          path: '/cockpit/blueprint',
          type: 'weilailantu-zonggui',
          id: '412'
        },
        {
          icon: 'shuziluansheng',
          title: '数字孪生',
          path: '/cockpit/digitaltwin',
          type: 'shuziluansheng',
          id: '413'
        },
        {
          icon: 'shengzhangdongtai',
          title: '生长动态',
          path: '/cockpit/growth',
          type: 'shengzhangdongtai',
          id: '414'
        },
        {
          icon: 'wanwuhulian',
          title: '万物互联',
          path: '/cockpit/iot',
          type: 'wanwuhulian',
          id: '415'
        }
      ],
      activeMenu: {},
      legendData: {},
      topMenuShow: true,
      allDataList: [],
      oldAllDataList: [],
      activeTool: '',
      selectLayer: null, // 树选择
      selectLayerId: null,
      isFirstChangeData: true, // 是否第一次数据切换
      dataList: [],
      activeData: {},
      showType: 1, // 0: 数据名称, 1: 底图影像
      blueShow: false,
      isRightSearchLoading: false
    }
  },
  async created() {
    const { viewer, layerManager, toolManager } =
      await getAction(this.defaultViewId)
    mapViewer[this.defaultViewId] =
      mapViewer[this.defaultViewId] || viewer

    _layerManager = layerManager
    this.setFeatureLayerOptions()
    this.$bus.$on('hideSearchPanel', (data) => {
      this.showSearchPanel = data
    })
    // this.$bus.$on('removeLayer', () => {
    //   this.setFeatureLayerOptions()
    // })

    New.$on('mapIndex', (data) => {
      if (data.list.length && this.showServiceList.length) {
        this.activeService = data.active
        return
      }
      this.mapServices = data.list
      if (this.mapServices.length > 4) {
        this.showServiceList = [...this.mapServices].slice(
          0,
          4
        )
      } else {
        this.showServiceList = [...this.mapServices]
      }
      this.activeService = data.active
      if (this.mapServices.length > 1) {
        this.show = true
        this.showType = 1
      }
      if (
        this.mapServices.length === 0 &&
        this.selectLayerId
      ) {
        this.show = true
        this.showType = 0
      }
    })
    New.$on('show', (data) => {
      this.show = data
    })
    New.$on('topic', (data) => {
      this.activeMenu.type = data.type
    })
    New.$on('layerList', (data) => {
      this.layerList = data
    })

    // layerManager.js移除layer时触发
    this.$bus.$on('handleBimDel', (id, serviceType) => {
      console.log('handleBimDel', id, serviceType)
      const index = this.allDataList.findIndex((item) => {
        return item.pkid === id
      })
      if (index > -1) {
        this.allDataList.splice(index, 1)
      }
      if (!id || id === this.selectLayerId) {
        this.clearData()
      }
    })

    this.$bus.$on('addLegendData', (legendDataList, id) => {
      this.legendData[id] = [...legendDataList]
      this.$bus.$emit(
        'addTreeItemLegendChildren',
        legendDataList,
        id
      )
    })

    // this.$bus.$on('showRealspaceService', (data) => {
    this.$bus.$on('showDataList', (data) => {
      console.log('显示数据名称选项', data)

      this.dealDataList(data)
    })
    this.$bus.$on('hideRealspaceService', (data) => {
      // console.log('隐藏realspace服务')
      // console.log(data)
      this.clearData()
    })

    this.$bus.$on('specialTypeBaseMap', () => {
      // console.log(
      //   '=========专题类型默认底图切换',
      //   this.$route.path
      // )
      const path = this.$route.path
      let type = ''
      if (path.indexOf('/panorama') !== -1) {
        type = 'chengshiquanjing'
      } else if (path.indexOf('/blueprint') !== -1) {
        type = 'weilailantu-zonggui'
      } else if (path.indexOf('/digitaltwin') !== -1) {
        type = 'shuziluansheng'
      } else if (path.indexOf('/growth') !== -1) {
        type = 'shengzhangdongtai'
      } else if (path.indexOf('/iot') !== -1) {
        type = 'wanwuhulian'
      }
      globalBaseMap[this.defaultViewId].getBasemapList(type)
    })

    globalBaseMap[this.defaultViewId] =
      globalBaseMap[this.defaultViewId] ||
      toolManager.basemapManager
    await globalBaseMap[this.defaultViewId].getBasemapList(
      ''
    )
    // 仅初始化驾驶舱时调用
    this.$bus.$emit('specialTypeBaseMap')

    // 获取数字孪生初始加载的数据
    topicDefaultList('shuziluansheng').then((res) => {
      this.defaultLayerList = res
    })
  },
  mounted() {
    this.menus.forEach((item) => {
      item.hasPri = checkMenuById(item.id)
    })
    this.menus = this.menus.filter((item) => item.hasPri)

    const find = this.menus.find((item) => {
      return item.path === this.$route.path
    })
    if (find) {
      this.activeMenu = find
    }
  },
  beforeDestroy() {
    New.$off('mapIndex')
    New.$off('show')
    New.$off('topic')
    New.$off('layerList')
    this.$bus.$off('addLegendData')
    this.$bus.$off('showDataList')
    this.$bus.$off('hideRealspaceService')
    this.$bus.$off('handleBimDel')
    this.$bus.$off('hideSearchPanel')
    this.$bus.$off('specialTypeBaseMap')
    this.legendData = {}
  },
  computed: {
    path() {
      return this.$route.path
    },
    defaultViewId() {
      return this.$store.state.layer.defaultViewId
    }
  },
  provide() {
    return {
      viewerId: this.defaultViewId,
      topic: this.activeMenu.type
    }
  },
  methods: {
    changeTool(icon) {
      this.activeTool = icon
      if (icon && icon !== 'daochutupian') {
        this.blueShow = this.topMenuShow = false
        New.$emit('blueShow', this.blueShow)
      } else {
        this.topMenuShow = true
      }
    },
    topShow() {
      if (this.activeTool) {
        return
      }
      this.topMenuShow = true
    },
    showService(data) {
      if (data.pkid !== this.activeService.pkid) {
        globalBaseMap[
          this.defaultViewId
        ].switchHistoryImagery(data.pkid)
      }
    },
    rightShow() {
      if (this.mapServices.length <= this.groupIndex * 4) {
        this.$message.error('已经到最后了')
      } else {
        this.groupIndex = this.groupIndex + 1
        if (
          this.mapServices.length <=
          this.groupIndex * 4
        ) {
          this.showServiceList = [
            ...this.mapServices
          ].slice(this.groupIndex * 4 - 4)
        } else {
          this.showServiceList = [
            ...this.mapServices
          ].slice(
            this.groupIndex * 4 - 4,
            this.groupIndex * 4
          )
        }
      }
    },
    leftShow() {
      if (this.groupIndex === 1) {
        this.$message.error('已经到最前面了')
      } else {
        this.groupIndex = this.groupIndex - 1
        this.showServiceList = [...this.mapServices].slice(
          this.groupIndex * 4 - 4,
          this.groupIndex * 4
        )
      }
    },
    dataListRightShow(value) {
      if (value) {
        if (
          value.dataList.length <=
          value.currentPage * 4
        ) {
          this.$message.error('已经到最后了')
        } else {
          value.currentPage += 1
          if (
            value.dataList.length <=
            value.currentPage * 4
          ) {
            value.showDataList = value.dataList.slice(
              value.currentPage * 4 - 4
            )
          } else {
            value.showDataList = value.dataList.slice(
              value.currentPage * 4 - 4,
              value.currentPage * 4
            )
          }
        }
      } else {
        if (
          this.dataList.length <=
          this.dataListGroupIndex * 4
        ) {
          this.$message.error('已经到最后了')
        } else {
          this.dataListGroupIndex =
            this.dataListGroupIndex + 1
          if (
            this.dataList.length <=
            this.dataListGroupIndex * 4
          ) {
            this.showDataList = [...this.dataList].slice(
              this.dataListGroupIndex * 4 - 4
            )
          } else {
            this.showDataList = [...this.dataList].slice(
              this.dataListGroupIndex * 4 - 4,
              this.dataListGroupIndex * 4
            )
          }
        }
      }
    },
    dataListLeftShow(value) {
      if (value) {
        if (value.currentPage === 1) {
          this.$message.error('已经到最前面了')
        } else {
          value.currentPage -= 1
          value.showDataList = value.dataList.slice(
            value.currentPage * 4 - 4,
            value.currentPage * 4
          )
        }
      } else {
        if (this.dataListGroupIndex === 1) {
          this.$message.error('已经到最前面了')
        } else {
          this.dataListGroupIndex =
            this.dataListGroupIndex - 1
          this.showDataList = [...this.dataList].slice(
            this.dataListGroupIndex * 4 - 4,
            this.dataListGroupIndex * 4
          )
        }
      }
    },
    mapOpenFun() {
      if (this.isShrink) {
        if (this.oldAllDataList.length) {
          this.allDataList = this.oldAllDataList
          this.oldAllDataList = []
        }
        this.isShrink = false
      } else {
        if (this.allDataList.length) {
          this.oldAllDataList = this.allDataList
          this.allDataList = []
        }
        this.isShrink = true
      }
    },
    openFun(index) {
      if (this.isShrink) {
        if (this.oldDataIndex > -1) {
          const tempObj =
            this.allDataList[this.allDataList.length - 1]
          this.allDataList.pop()
          this.allDataList.splice(
            this.oldDataIndex,
            0,
            tempObj
          )
          this.oldDataIndex = -1
        }
        this.isShrink = false
      } else {
        const lastIndex = this.allDataList.length - 1
        if (lastIndex !== index) {
          const arr = this.allDataList[index]
          this.allDataList.splice(index, 1)
          this.allDataList.push(arr)
          this.oldDataIndex = index
        }
        this.isShrink = true
      }
    },
    go(path) {
      // if (path !== 'search') {
      //   this.showSearchPanel = false
      //   this.$bus.$emit('togglePanel', false)
      //   if (path !== this.path) {
      //     this.$router.push(path)
      //   }
      // } else {
      //   this.showSearchPanel = true
      //   this.$bus.$emit('togglePanel', true)
      // }
    },
    onAddressKeyDown() {
      if (this.addressSearchKeyword) {
        // console.log('搜索', this.searchType, this.searchKeyword)
        if (this.allAddressData.length) {
          this.filterAddressResult()
        } else {
          this.isRightSearchLoading = true
          axios
            .get(ADDRESS_QUERY_URL + '/layers.json')
            .then((res) => {
              if (res.data) {
                const namesParams = []
                res.data[0].subLayers.layers.forEach(
                  (subLayer) => {
                    namesParams.push(subLayer.name)
                  }
                )
                this.addressSearchResult.splice(
                  0,
                  this.addressSearchResult.length
                )
                this.removeAllSearchGeojson()
                const param =
                  new SuperMap.QueryBySQLParameters({
                    queryParams: namesParams.map(
                      (namesParam) => {
                        return {
                          attributeFilter: 'SmID != "0"',
                          name: namesParam
                        }
                      }
                    )
                  })
                L.supermap
                  .queryService(ADDRESS_QUERY_URL)
                  .queryBySQL(param, (result) => {
                    // console.log('地名地址', result)
                    this.allAddressData.push(
                      ...result.result.recordsets
                    )
                    this.filterAddressResult()
                  })
              }
              this.isRightSearchLoading = false
            })
            .catch((err) => {
              this.$message.error('查询失败')
              console.error(err)
              this.isRightSearchLoading = false
            })
        }
      } else {
        // console.log('清空搜索')
        this.addressSearchResult.splice(
          0,
          this.addressSearchResult.length
        )
      }
    },
    // 过滤地名地址搜索结果
    filterAddressResult() {
      this.allAddressData.forEach((recordset) => {
        const features = recordset.features
        if (features && features.features.length > 0) {
          // console.log('features', features)
          features.features.forEach((feature) => {
            const name = feature.properties['TextString']
            if (
              name.indexOf(this.addressSearchKeyword) !== -1
            ) {
              // console.log('匹配成功', feature)
              this.addressSearchResult.push({
                id: this.generateUUID(),
                name: name,
                address: '',
                geojson: feature
              })
            }
          })
        }
      })
    },
    onAddressSearchResultClick(item) {
      // console.log('click', item)
      Cesium.GeoJsonDataSource.load(item.geojson, {
        markerSize: 0
      }).then((dataSource) => {
        mapViewer[this.defaultViewId].dataSources.add(
          dataSource
        )
        previousGeojsonList.push(dataSource)
        mapViewer[this.defaultViewId].flyTo(dataSource)
        const entities = dataSource.entities.values
        entities.forEach((entity) => {
          if (entity.polygon) {
            entity.polygon.extrudedHeight = 0.1
            entity.polygon.material =
              Cesium.Color.WHITE.withAlpha(0.3)
            entity.polygon.outlineWidth = 3
            entity.polygon.outlineColor = Cesium.Color.RED
            // stroke: Cesium.Color.RED,
            // strokeWidth: 3,
            // fill: Cesium.Color.WHITE.withAlpha(0.3)
          } else if (entity.polyline) {
            // console.log(
            //   'positions',
            //   entity.polyline.positions
            // )
            entity.polyline.material =
              Cesium.Color.WHITE.withAlpha(0.7)
            entity.polyline.width = 5
          } else if (entity.point) {
            // console.log(
            //   'the entity has point'
            // )
          } else {
            // entity.show = false
            entity.point = new Cesium.PointGraphics({
              color: Cesium.Color.WHITE.withAlpha(0.5),
              pixelSize: 10,
              outlineWidth: 2,
              outlineColor: Cesium.Color.RED,
              heightReference:
                Cesium.HeightReference.CLAMP_TO_GROUND
            })
          }
        })
      })
    },
    onFeatureLayerSelectVisibleChange(val) {
      if (val) {
        this.setFeatureLayerOptions()
      }
    },
    setFeatureLayerOptions() {
      this.$nextTick(() => {
        // const layerList = _layerManager.layers.reverse().filter((item) => (item.from === '3' && item.dataService) || item.from !== '3')
        const layerList = _layerManager.layers
          .reverse()
          .filter((item) => item.from !== '3') // 三维服务属性数据量过大，暂时屏蔽
        console.log('图层', layerList)
        this.featureSearchLayerOptions.splice(
          0,
          this.featureSearchLayerOptions.length
        )
        this.featureSearchLayerOptions.push(
          ...layerList.map((item) => {
            return {
              label: item.title,
              value: item.id,
              data: item
            }
          })
        )
        if (
          this.featureSearchLayerOptions.every(
            (item) => item.value !== this.featureSearchLayer
          )
        ) {
          this.featureSearchLayer = ''
        }
      })
    },
    async onFeatureKeyDown() {
      if (this.featureSearchKeyword) {
        const find = this.featureSearchLayerOptions.find(
          (item) => item.value === this.featureSearchLayer
        )
        if (find) {
          // console.log(
          //   '搜索',
          //   find,
          //   find.label,
          //   this.featureSearchKeyword
          // )
          this.isRightSearchLoading = true
          // retrieveDataServiceList({
          //   pageIndex: 1,
          //   pageSize: 999,
          //   serviceId: find.data.id
          // })
          //   .then(async (res) => {
          const currentData = _layerManager.get(find.value)
          console.log(currentData)
          if (!currentData.id) {
            this.$message.warning(
              '未读取到该服务的数据服务配置'
            )
            this.isRightSearchLoading = false
            return
          }
          const res =
            currentData.dataList[
              currentData.currentDataIndex
            ]
          if (res.resourceServiceDataInfoList.length) {
            for await (const dataServiceConfig of res.resourceServiceDataInfoList) {
              // console.log(`搜索"${this.featureSearchKeyword}", ${dataServiceConfig.serviceDataUrl}`)
              const dataService =
                dataServiceConfig.serviceDataUrl
              const dataServiceUrl =
                dataService.substring(
                  0,
                  dataService.lastIndexOf('/datasources/')
                ) +
                '/featureResults.rjson?returnContent=true&toIndex=-1'
              // console.log('请求地址', dataServiceUrl)
              const dataSourceAndDataSet = dataService
                .substring(
                  dataService.lastIndexOf('/datasources/') +
                    '/datasources/'.length
                )
                .split('/datasets/')
                .map((i) => decodeURI(i))
              const sqlParameter = {
                datasetNames: [
                  `${dataSourceAndDataSet.join(':')}`
                ],
                getFeatureMode: 'SQL',
                queryParameter: {
                  attributeFilter: 'SmID != -1'
                }
              }
              console.log(sqlParameter)
              await axios
                .post(
                  dataServiceUrl,
                  JSON.stringify(sqlParameter)
                )
                .then((res) => {
                  // console.log('查询结果', res)
                  this.featureSearchResult = []
                  if (res.data && res.data.featureCount) {
                    for (const feature of res.data
                      .features) {
                      const valueIndex =
                        feature.fieldValues.findIndex(
                          (field) =>
                            field.indexOf(
                              this.featureSearchKeyword
                            ) !== -1
                        )
                      if (valueIndex !== -1) {
                        // console.log('找到数据', valueIndex, feature)
                        this.featureSearchResult.push({
                          dataServicePkid:
                            dataServiceConfig.pkid,
                          SmID: feature.fieldValues[0],
                          resultKey:
                            feature.fieldNames[valueIndex],
                          resultValue:
                            feature.fieldValues[valueIndex],
                          geometry: feature.geometry
                        })
                      }
                    }
                  }
                })
                .catch((err) => {
                  this.featureSearchResult = []
                  console.error(err)
                  this.$message.error('查询失败')
                  this.isRightSearchLoading = false
                })
            }
            console.log(
              '列表显示',
              this.featureSearchResult
            )
          } else {
            this.$message.warning(
              '未读取到该服务的数据服务配置'
            )
            this.isRightSearchLoading = false
          }
          this.isRightSearchLoading = false
          // })
          // .catch((err) => {
          //   this.$message.error(err)
          //   console.error(err)
          //   this.isRightSearchLoading = false
          // })
          // if (find.data.from !== '3') {
          //   // 不是BIM
          //   axios
          //     .get(
          //       find.data.layer.imageryProvider.url +
          //         'layers.json'
          //     )
          //     .then((res) => {
          //       // console.log('res.data', res.data)
          //       if (res.data) {
          //         // console.log(res.data[0].subLayers.layers)
          //         // 待查询的数据名(图层名@数据源名)
          //         this.featureSearchResult.splice(
          //           0,
          //           this.featureSearchResult.length
          //         )
          //         this.removeAllEntity()
          //         const namesParams = []
          //         res.data[0].subLayers.layers.forEach(
          //           (subLayer) => {
          //             // console.log('name', subLayer.name)
          //             namesParams.push(subLayer.name)
          //           }
          //         )
          //         axios
          //           .post(
          //             find.data.layer.imageryProvider.url +
          //               '/queryResults.json?returnContent=true',
          //             {
          //               queryMode: 'SqlQuery',
          //               queryParameters: {
          //                 customParams: null,
          //                 prjCoordSys: null,
          //                 expectCount: 100000,
          //                 networkType: 'LINE',
          //                 queryOption:
          //                   'ATTRIBUTEANDGEOMETRY',
          //                 queryParams: namesParams.map(
          //                   (namesParam) => {
          //                     return {
          //                       name: namesParam,
          //                       attributeFilter:
          //                         'SmID != "0"'
          //                     }
          //                   }
          //                 ),
          //                 startRecord: 0,
          //                 holdTime: 10,
          //                 returnCustomResult: false,
          //                 returnFeatureWithFieldCaption: true
          //               }
          //             }
          //           )
          //           .then((res) => {
          //             console.log('res', res)
          //             if (res.data) {
          //               let features = []
          //               res.data.recordsets.forEach(
          //                 (recordset) => {
          //                   const feature =
          //                     recordset.features
          //                   if (
          //                     feature &&
          //                     feature.length > 0
          //                   ) {
          //                     // console.log('feature', feature)
          //                     feature.forEach((item) => {
          //                       const filter = {}
          //                       item.fieldNames.forEach(
          //                         (fieldName, index) => {
          //                           filter[fieldName] =
          //                             item.fieldValues[
          //                               index
          //                             ]
          //                         }
          //                       )
          //                       filter.geometry =
          //                         item.geometry
          //                       features.push(filter)
          //                     })
          //                   }
          //                 }
          //               )
          //               features = features.filter(
          //                 (item) => {
          //                   return Object.values(item).some(
          //                     (temp) =>
          //                       typeof temp === 'string' &&
          //                       temp.indexOf(
          //                         this.featureSearchKeyword
          //                       ) !== -1
          //                   )
          //                 }
          //               )
          //               features.forEach((item) => {
          //                 const keys = Object.keys(item)
          //                 const values = Object.values(item)
          //                 const index = values.findIndex(
          //                   (item) =>
          //                     item.indexOf(
          //                       this.featureSearchKeyword
          //                     ) !== -1
          //                 )
          //                 item['resultKey'] = keys[index]
          //                 item['resultValue'] =
          //                   values[index]
          //               })
          //               this.featureSearchResult.push(
          //                 ...features
          //               )
          //             }
          //           })
          //       }
          //     })
          // } else {
          //   // 是BIM
          //   axios
          //     .get(find.data.dataService + '/datasets.json')
          //     .then((res) => {
          //       console.log(res)
          //       if (res.data) {
          //         this.featureSearchResult.splice(
          //           0,
          //           this.featureSearchResult.length
          //         )
          //         this.removeAllEntity()
          //         const featureQueryUrl =
          //           find.data.dataService.substring(
          //             0,
          //             find.data.dataService.lastIndexOf(
          //               '/datasources/'
          //             )
          //           ) +
          //           '/featureResults.rjson?returnContent=true'
          //         console.log('请求地址', featureQueryUrl)
          //         const dataSourceAndDataSetList = []
          //         res.data.childUriList.forEach((item) => {
          //           const dataSourceAndDataSet = item
          //             .substring(
          //               item.lastIndexOf('/datasources/') +
          //                 '/datasources/'.length
          //             )
          //             .split('/datasets/')
          //             .map((item) => decodeURI(item))
          //           // console.log('数据源:数据集', dataSourceAndDataSet)
          //           dataSourceAndDataSetList.push(
          //             dataSourceAndDataSet.join(':')
          //           )
          //         })
          //         console.log(
          //           '数据源:数据集',
          //           dataSourceAndDataSetList
          //         )
          //         const sqlParameter = {
          //           datasetNames: dataSourceAndDataSetList,
          //           getFeatureMode: 'SQL',
          //           queryParameter: {
          //             attributeFilter: 'SmID!=123'
          //           }
          //         }
          //         console.log(sqlParameter)
          //         const queryData =
          //           JSON.stringify(sqlParameter)
          //         axios
          //           .post(featureQueryUrl, queryData)
          //           .then((res) => {
          //             console.log('BIM要素查询结果', res)
          //           })
          //       }
          //     })
          // }
        }
      } else {
        this.featureSearchResult.splice(
          0,
          this.featureSearchResult.length
        )
      }
    },
    onFeatureSearchResultClick(item) {
      this.removeAllEntity()
      console.log('click', item)
      if (item.geometry) {
        if (item.geometry.type.indexOf('POINT') !== -1) {
          const entity = new Cesium.Entity({
            position: Cesium.Cartesian3.fromDegrees(
              item.geometry.points[0].x,
              item.geometry.points[0].y,
              item.geometry.points[0].z
            ),
            point: {
              color:
                Cesium.Color.fromCssColorString('#3388ff'),
              pixelSize: 10,
              outlineColor:
                Cesium.Color.fromCssColorString('#ffffff'),
              outlineWidth: 2,
              disableDepthTestDistance:
                Number.POSITIVE_INFINITY // 一直显示，不被地形等遮挡
            }
          })
          mapViewer[this.defaultViewId].entities.add(entity)
          previousEntity = entity
          mapViewer[this.defaultViewId].flyTo(entity)
        } else if (
          item.geometry.type.indexOf('LINE') !== -1
        ) {
          const positions = []
          item.geometry.points.forEach((item) => {
            positions.push(item.x)
            positions.push(item.y)
          })
          const entity = new Cesium.Entity({
            polyline: {
              positions:
                Cesium.Cartesian3.fromDegreesArray(
                  positions
                ),
              width: 3,
              followSurface: true,
              material:
                Cesium.Color.fromCssColorString('#3388ff'),
              clampToGround: true
            }
          })
          mapViewer[this.defaultViewId].entities.add(entity)
          previousEntity = entity
          mapViewer[this.defaultViewId].flyTo(entity)
        } else if (
          item.geometry.type.indexOf('REGION') !== -1
        ) {
          const positions = []
          item.geometry.points.forEach((item) => {
            positions.push(item.x)
            positions.push(item.y)
          })
          const entity = new Cesium.Entity({
            polygon: {
              hierarchy:
                Cesium.Cartesian3.fromDegreesArray(
                  positions
                ),
              extrudeHeight: 0.5,
              material:
                Cesium.Color.fromCssColorString('#3388ff'),
              outline: true,
              outlineColor: Cesium.Color.YELLOW,
              fill: true
            },
            classificationType:
              Cesium.ClassificationType.BOTH
          })
          mapViewer[this.defaultViewId].entities.add(entity)
          previousEntity = entity
          mapViewer[this.defaultViewId].flyTo(entity)
        }
      }
    },
    removeAllSearchGeojson() {
      previousGeojsonList.forEach((item) => {
        mapViewer[this.defaultViewId].dataSources.remove(
          item,
          false
        )
      })
      previousGeojsonList = []
    },
    removeAllEntity() {
      if (previousEntity) {
        // previousEntity.show = false
        mapViewer[this.defaultViewId].entities.remove(
          previousEntity
        )
        previousEntity = null
      }
    },
    handleMenuItemClick(index) {
      this.activeMenu = this.menus[index]
      if (this.$route.path !== this.menus[index].path) {
        this.$router.push(this.menus[index].path)
      }
      // else if (this.$route.path === this.menus[index].path && index === 1&&this.blueShow) {
      //   this.blueShow = !this.blueShow
      //   New.$emit('blueShow', this.blueShow)
      // }
    },
    doBlueShow(index) {
      // if (index !== 1) {
      //   return
      // }
      // this.blueShow = true
      // New.$emit('blueShow', this.blueShow)
    },
    doBlueHide(index) {
      // if (index !== 1) {
      //   return
      // }
      // this.blueShow = false
      // New.$emit('blueShow', this.blueShow)
    },
    // 处理阶段
    dealDataList(data) {
      // const layerList = JSON.parse(data.serviceUrl)
      // // 查找树渲染的图层
      // // const activeDataIndex = layerList.findIndex(
      // //   (item) => !!item.serviceUrl
      // // )
      // const activeDataIndex =
      //   Number(
      //     this.dataChangePkid.charAt(
      //       this.dataChangePkid.length - 1
      //     )
      //   ) ||
      //   layerList.findIndex((item) => !!item.serviceUrl)
      // const selectLayer = layerList[activeDataIndex]
      // // 处理阶段
      // const dataList = layerList.map((item, index) => {
      //   item.id = 'BIM' + index
      //   item.stageId = 'BIM' + index
      //   item.layerId = data.pkid
      //   // item.pkid = 'BIM' + index;
      //   item.pkid = data.pkid
      //   item.title = 'BIM' + index
      //   item.name = 'BIM' + index
      //   item.sourceName = data.sourceName
      //   item.from = data.from
      //   item.serviceType = data.serviceType
      //   item.bimType = data.bimType
      //   item.disabled = !item.serviceUrl
      //   return item
      // })
      // this.selectLayer = selectLayer
      // this.selectLayerId = data.pkid
      // this.dataList = dataList
      // if (this.dataList && this.dataList.length > 0) {
      //   this.showType = 0
      // }
      // this.activeData = dataList[activeDataIndex]
      // this.isFirstChangeData = true
      // // this.setBimStyle()
      // console.log(this.dataList)
      // this.setRightActiveTool('Property')

      const layerList = data.dataList
      // const activeDataIndex =
      //   Number(
      //     this.dataChangePkid.charAt(
      //       this.dataChangePkid.length - 1
      //     )
      //   ) ||
      //   layerList.findIndex((item) => !!item.serviceUrl)
      // 处理阶段
      // const dataList = layerList.map((item, index) => {
      //   item.id = 'BIM' + index
      //   item.stageId = 'BIM' + index
      //   item.layerId = data.pkid
      //   // item.pkid = 'BIM' + index;
      //   item.pkid = data.pkid
      //   item.title = 'BIM' + index
      //   item.name = 'BIM' + index
      //   item.sourceName = data.sourceName
      //   item.from = data.from
      //   item.serviceType = data.serviceType
      //   item.bimType = data.bimType
      //   item.disabled = !item.serviceUrl
      //   return item
      // })

      // this.selectLayer = layerList[activeDataIndex]
      this.selectLayer = layerList[0]
      this.selectLayerId = data.pkid
      this.dataList = layerList
      if (this.dataList && this.dataList.length > 0) {
        this.showType = 0
      }
      // this.activeData = layerList[activeDataIndex]
      this.activeData = layerList[0]
      this.isFirstChangeData = true
      console.log(this.dataList)
      this.setRightActiveTool('Property')

      if (this.dataList.length > 4) {
        this.showDataList = [...this.dataList].slice(0, 4)
      } else {
        this.showDataList = [...this.dataList]
      }
      const tempData = {
        name: data.sourceName,
        dataList: data.dataList,
        showDataList: this.showDataList,
        currentIndex: 0,
        pkid: data.pkid,
        currentPage: 1
      }
      if (data.dataList.length > 1) {
        this.allDataList.push(tempData)
      }

      if (this.dataList.length > 1) {
        this.show = true
        this.showType = 0
      }
      if (
        this.dataList.length === 0 &&
        this.selectLayerId
      ) {
        this.show = true
        this.showType = 0
      }
    },
    // 清除数据
    clearData() {
      this.selectLayer = null
      this.selectLayerId = null
      this.dataList = []
      this.showType = 1
      // New.$emit('show', true)
      this.activeData = {}
      this.isFirstChangeData = true
      // this.activeTool = ''
      // this.rightHide = true
      // this.multiDetailData = []
      // this.multiDetailIndex = -1
      // this.bimNumber = ''
      this.setRightActiveTool('')
    },
    // 阶段点击
    dataClickHandle(data, index, index2) {
      // console.log(data, index, index2)
      // console.log(data)
      // console.log('dataClickHandle', data, this.activeData);

      this.$bus.$emit('changePropertiesTableData')
      const currentIndex =
        (this.allDataList[index].currentPage - 1) * 4 +
        index2
      if (index > -1) {
        if (
          this.allDataList[index].currentIndex ===
          currentIndex
        ) {
          this.$bus.$emit(
            'activeDataChange',
            this.allDataList[index].dataList[
              this.allDataList[index].currentIndex
            ]
          )
          return
        }
        // console.log(this.allDataList[index].currentIndex)
        if (!data.serviceUrl) {
          return
        }
        this.setRightActiveTool('Property')
        // //第一次阶段切换,移除bim树添加的图层
        // if (this.isFirstChangeData) {
        // console.log('isFirstChangeData', this.isFirstChangeData);
        // this.isFirstChangeData = false
        const currentLayer = _layerManager.get(
          this.allDataList[index].pkid
        )
        _layerManager.del(this.allDataList[index].pkid)
        // console.log('currentLayer', currentLayer)
        currentLayer.serviceUrl = data.serviceUrl
        currentLayer.signService = data.signService
        currentLayer.pkid = currentLayer.id
        currentLayer.sourceName = currentLayer.title
        currentLayer.currentDataIndex = currentIndex
        // console.log(currentLayer)
        _layerManager.add(currentLayer)

        this.getLegendLayer(
          currentLayer.signService,
          currentLayer
        )

        this.allDataList[index].currentIndex = currentIndex
      } else {
        if (data.pkid === this.activeData.pkid) {
          // 如果点击的是同一个数据
          return
        }

        if (
          this.$route.path.indexOf(
            '/cockpit/digitaltwin'
          ) !== -1
        ) {
          // 如果是数字孪生切换了数据名称
          // 先将当前阶段存储到全局
          // 遍历删除已添加图层
          const res = this.defaultLayerList
          this.dataChangePkid = data.id
          if (res.success) {
            const activeIds = []
            _layerManager.layers.forEach((layer) => {
              activeIds.push(layer.id)
            })
            const defaultIds = []
            res.data &&
              res.data.map((item) => {
                defaultIds.push(item.pkid)
              })

            const delIds = activeIds.filter((activeId) => {
              return defaultIds.every((defaultId) => {
                return defaultId !== activeId
              })
            })

            delIds.forEach((id) => {
              _layerManager.del(id)
            })
            console.log(delIds)
            const activeDataIndex = Number(
              this.dataChangePkid.charAt(
                this.dataChangePkid.length - 1
              )
            )
            // 遍历当前处于选中的数据列表
            // 取得数据列表当中的数据
            // 构建图层
            const dataList = []
            this.layerList.forEach((res) => {
              if (res.serviceUrl.indexOf('[{') !== -1) {
                const stages = JSON.parse(res.serviceUrl)
                const item = { ...stages[activeDataIndex] }
                item.id = 'BIM' + activeDataIndex
                item.stageId = 'BIM' + activeDataIndex
                item.layerId = res.pkid
                item.pkid = res.pkid
                item.title = 'BIM' + activeDataIndex
                item.name = 'BIM' + activeDataIndex
                item.sourceName = res.sourceName
                item.from = res.from
                item.serviceType = res.serviceType
                item.bimType = res.bimType
                item.disabled =
                  !stages[activeDataIndex].serviceUrl
                dataList.push(item)
              }
            })

            // 将图层渲染到图上
            dataList.forEach((stage) => {
              if (!stage.disabled) {
                _layerManager.add(stage)
                this.activeData = stage
              }
            })
          }
        } else {
          this.dataChangePkid = ''

          // this.activeData =
          //   this.activeData &&
          //   this.activeData.id === data.id
          //     ? undefined
          //     : data
          if (!data.serviceUrl) {
            return
          }
          this.setRightActiveTool('Property')
          // //第一次阶段切换,移除bim树添加的图层
          // if (this.isFirstChangeData) {
          // console.log('isFirstChangeData', this.isFirstChangeData);
          // this.isFirstChangeData = false
          const currentLayer = _layerManager.get(
            this.selectLayerId
          )
          _layerManager.del(this.selectLayerId)
          console.log('currentLayer', currentLayer)
          this.activeData = data
          console.log(this.activeData)
          currentLayer.serviceUrl = data.serviceUrl
          currentLayer.signService = data.signService
          currentLayer.pkid = currentLayer.id
          currentLayer.sourceName = currentLayer.title
          currentLayer.currentDataIndex =
            this.dataList.findIndex(
              (item) => item.pkid === this.activeData.pkid
            )
          _layerManager.add(currentLayer)

          this.getLegendLayer(
            currentLayer.signService,
            currentLayer
          )
          // let selectLayer = this._layerManager._layers.get(this.selectLayerId);
          // // this._layerManager._layers.delete(this.selectLayerId);
          // // console.log('first', this._layerManager._layers)
          // let name = selectLayer.name; //主图层隐藏
          // name.forEach((item) => {
          //   this._viewer.scene.layers.remove(item)
          // })
          // } else {
          //   _layerManager.del(this.selectLayerId)
          // }
        }
      }
    },
    getLegendLayer(url, data) {
      axios
        .get(url + '/layers.json')
        .then(async (res) => {
          if (res.data) {
            const subLayerNames = []
            const subLayers = []
            if (
              res.data &&
              res.data.length &&
              res.data[0].subLayers &&
              res.data[0].subLayers.layers.length
            ) {
              res.data[0].subLayers.layers.forEach(
                (subLayer) => {
                  subLayerNames.push(
                    subLayer.name + '@@' + res.data[0].name
                  )
                  subLayers.push(subLayer)
                }
              )
              // console.log('sublayers', subLayers)
              const legendDataList = []
              for await (const [
                subLayerIndex,
                subLayer
              ] of subLayers.entries()) {
                if (
                  subLayer.theme &&
                  subLayer.theme.items &&
                  subLayer.theme.items instanceof Array &&
                  subLayer.theme.items.length
                ) {
                  // 配置了专题图
                  for await (const item of subLayer.theme
                    .items) {
                    const tempLegendData = {
                      // name: subLayer.caption,
                      name: item.caption
                    }

                    let resourceType = ''
                    let requestNetworkImage = false
                    if (
                      subLayer.datasetInfo.type ===
                        'POINT' ||
                      subLayer.datasetInfo.type ===
                        'POINT3D'
                    ) {
                      resourceType = 'SYMBOLMARKER'
                      if (item.style.markerSymbolID !== 0) {
                        requestNetworkImage = true
                      }
                    } else if (
                      subLayer.datasetInfo.type ===
                        'LINE' ||
                      subLayer.datasetInfo.type === 'LINE3D'
                    ) {
                      resourceType = 'SYMBOLLINE'
                      if (item.style.lineSymbolID !== 0) {
                        requestNetworkImage = true
                      }
                    } else if (
                      subLayer.datasetInfo.type ===
                        'REGION' ||
                      subLayer.datasetInfo.type ===
                        'REGION3D'
                    ) {
                      resourceType = 'SYMBOLFILL'
                      if (item.style.fillSymbolID !== 0) {
                        requestNetworkImage = true
                      }
                    }
                    if (requestNetworkImage) {
                      try {
                        await axios
                          .get(
                            url +
                              `/symbol.json?resourceType=${resourceType}&style=` +
                              JSON.stringify(item.style) +
                              '&transparent=true'
                          )
                          .then((res) => {
                            // console.log('图例json数据', res)
                            if (
                              // res.status === 200 &&
                              res.data &&
                              res.data.resourceImageUrl
                            ) {
                              tempLegendData.img =
                                res.data.resourceImageUrl
                            }
                          })
                      } catch (e) {
                        console.error('请求图例图片错误', e)
                      }
                    } else {
                      if (resourceType === 'SYMBOLLINE') {
                        tempLegendData.color =
                          item.style.lineColor
                      } else if (
                        resourceType === 'SYMBOLFILL'
                      ) {
                        tempLegendData.color =
                          item.style.fillForeColor
                      }
                    }

                    // if (
                    //   item.style.markerSymbolID === 0 &&
                    //   item.style.lineSymbolID === 0 &&
                    //   item.style.fillSymbolID === 0
                    // ) {
                    //   if (
                    //     subLayer.datasetInfo.type === 'LINE'
                    //   ) {
                    //     tempLegendData.color =
                    //       item.style.lineColor
                    //   } else if (
                    //     subLayer.datasetInfo.type ===
                    //     'REGION'
                    //   ) {
                    //     tempLegendData.color =
                    //       item.style.fillForeColor
                    //   }
                    // } else {
                    //   let resourceType = ''
                    //   if (item.style.markerSymbolID !== 0) {
                    //     resourceType = 'SYMBOLMARKER'
                    //   } else if (
                    //     item.style.lineSymbolID !== 0
                    //   ) {
                    //     resourceType = 'SYMBOLLINE'
                    //   } else if (
                    //     item.style.fillSymbolID !== 0
                    //   ) {
                    //     resourceType = 'SYMBOLFILL'
                    //   }
                    //   try {
                    //     await axios
                    //       .get(
                    //         url +
                    //           `/symbol.json?resourceType=${resourceType}&style=` +
                    //           JSON.stringify(item.style) +
                    //           '&transparent=true'
                    //       )
                    //       .then((res) => {
                    //         // console.log('图例json数据', res)
                    //         if (
                    //           // res.status === 200 &&
                    //           res.data &&
                    //           res.data.resourceImageUrl
                    //         ) {
                    //           tempLegendData.img =
                    //             res.data.resourceImageUrl
                    //         }
                    //       })
                    //   } catch (e) {
                    //     console.error('请求图例图片错误', e)
                    //   }
                    // }
                    legendDataList.push(tempLegendData)
                  }
                } else {
                  // 未配置专题图
                  const subLayerName = subLayerNames[
                    subLayerIndex
                  ].replaceAll('#', '.')
                  legendDataList.push({
                    name: subLayer.caption,
                    img:
                      url +
                      '/layers/' +
                      subLayerName +
                      '/legend.png?width=30&height=30'
                  })
                }
              }

              if (legendDataList.length) {
                const tempList = legendDataList.map(
                  (item) => {
                    return {
                      img: item.img,
                      color: item.color,
                      name: item.name
                      // pkid: data.pkid + '-' + index
                    }
                  }
                )

                this.$bus.$emit(
                  'addLegendData',
                  tempList,
                  data.pkid
                )
              } else {
                this.$bus.$emit(
                  'addLegendData',
                  [],
                  data.pkid
                )
              }
            } else {
              this.$bus.$emit(
                'addLegendData',
                [],
                data.pkid
              )
            }
          } else {
            this.$bus.$emit('addLegendData', [], data.pkid)
          }
        })
        .catch((err) => {
          this.$bus.$emit('addLegendData', [], data.pkid)
          console.error('查询子图层失败', err)
        })
    },
    // 右侧工具栏
    setRightActiveTool(toolName) {
      if (
        this.$route.path.indexOf('/cockpit/digitaltwin') !==
        -1
      ) {
        // 当前模块为数字孪生
        console.log('数字孪生')
        this.$bus.$emit('changeLeftActiveTool', toolName)
      }
    }
  },
  watch: {
    $route: {
      handler(val) {
        this.show = false
        this.dataList = []
        this.mapServices = []
        this.showServiceList = []
        this.showDataList = []
        this.allDataList = []
        this.oldDataIndex = -1
        this.oldAllDataList = []
        this.isShrink = true

        this.topMenuShow = true
        // 移除已加载的服务
        _layerManager.del()
        _layerManager.layers.forEach((e) => {
          this.$bus.$emit('handleBimDel', e.id)
          // _layerManager.del(e.id)
        })
        this.legendData = {}
        // 设置底图为无底图
        if (
          globalBaseMap[this.defaultViewId]
            .currentBasemapIndex !== 0
        ) {
          globalBaseMap[this.defaultViewId].switchBasemap(0)
        }
        const path = val.path
        let type = ''
        if (path.indexOf('/panorama') !== -1) {
          type = 'chengshiquanjing'
        } else if (path.indexOf('/blueprint') !== -1) {
          type = 'weilailantu-zonggui'
        } else if (path.indexOf('/digitaltwin') !== -1) {
          type = 'shuziluansheng'
        } else if (path.indexOf('/growth') !== -1) {
          type = 'shengzhangdongtai'
        } else if (path.indexOf('/iot') !== -1) {
          type = 'wanwuhulian'
        }
        globalBaseMap[this.defaultViewId].getBasemapList(
          type
        )
        // console.log('=========路由变化', val)
      }
    },
    addressSearchKeyword: {
      handler(val) {
        if (!val) {
          this.addressSearchResult.splice(
            0,
            this.addressSearchResult.length
          )
          this.removeAllSearchGeojson()
        }
      }
    },
    featureSearchLayer: {
      handler() {
        this.featureSearchKeyword = ''
        this.featureSearchResult =
          this.featureSearchResult.splice(
            0,
            this.featureSearchResult.length
          )
      }
    },
    featureSearchKeyword: {
      handler(val) {
        if (!val) {
          this.featureSearchResult.splice(
            0,
            this.featureSearchResult.length
          )
          this.removeAllEntity()
        }
      }
    },
    showSearchPanel: {
      handler(val) {
        if (!val) {
          this.removeAllSearchGeojson()
          this.removeAllEntity()
        }
      }
    },
    activeData: {
      handler(newVal, oldVal) {
        // console.log('active', newVal);
        // if (oldVal) {
        // this._layerManager.del(oldVal.pkid)
        // }
        this.$bus.$emit('activeDataChange', newVal)
        console.log('activeData改变')
        if (newVal) {
          if (
            this.$route.path.indexOf(
              '/cockpit/digitaltwin'
            ) !== -1
          ) {
            if (!newVal.disabled) {
              _layerManager.add(newVal)
              this.activeData = newVal
            }
          }
          if (!this.isFirstChangeData) {
            _layerManager.add(newVal)
          }
          // //阶段切换时，保持树节点选中
          // setTimeout(() => {
          //   if (this.$refs.tree) {
          //     this.$refs.tree.setNodeChecked(newVal.pkid)
          //   }
          // })
        }
      },
      deep: true
    }
    // layerList: {
    //   handler(newVal) {
    //     this.maxBimData = 0
    //     newVal.forEach((layer) => {
    //       if (layer.bimType) {
    //         const serviceUrlList = JSON.parse(
    //           layer.serviceUrl
    //         )
    //         const mostIndex =
    //           serviceUrlList.findIndex((item) => {
    //             return !item.serviceUrl
    //           }) - 1
    //         if (this.maxBimData) {
    //           if (this.maxBimData - mostIndex < 0) {
    //             this.maxBimData = mostIndex
    //           }
    //         } else {
    //           this.maxBimData = mostIndex
    //         }
    //       }
    //     })
    //   },
    //   deep: true
    // }
  }
}
</script>

<style lang="scss" scoped>
.cockpit {
  &-menu-background {
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    height: 95px;
  }

  &-menu {
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);

    &-item {
      cursor: pointer;
      margin-top: 15px;

      .title {
        font-size: 18px;
        font-weight: bold;
        color: white;
        text-shadow: 0 3px 5px rgba(0, 0, 0, 0.35);
        margin-left: 6px;
      }

      .separator {
        color: #778d9d;
        font-size: 12px;
        font-weight: bold;
        margin: 0 24px;
      }
    }

    &-item.active {
      background-image: url('~@/assets/img/background-cockpit-menu-item-active.png');
      background-size: contain;
      background-repeat: no-repeat;

      ::v-deep {
        .svg-icon {
          fill: #3aa1fe;
        }
      }

      .title {
        color: #3aa1fe;
      }
    }

    .el-button {
      border-radius: 4px;
      background-color: #192f3d;
      border-color: #192f3d;

      ::v-deep {
        span {
          color: white;
        }
      }

      &:not(:last-of-type) {
        margin-right: 10px;
      }
    }

    .el-button.active {
      background-color: #00baff;
      border-color: #00baff;
    }
  }

  .navList {
    position: fixed;
    left: 0;
    top: 60px;
    width: 48px;
    height: calc(100vh - 60px);
    display: flex;
    flex-direction: column;
    align-items: center;
    border-right: 1px solid rgba(255, 255, 255, 0.2);
    background: rgba(25, 47, 61, 0.85);
    z-index: 999;

    & > div:first-child {
      border-top: 1px solid rgba(255, 255, 255, 0.2);
    }

    & > div {
      border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    }

    &-nav {
      width: 100%;
      padding: 10px 0;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      font-size: 14px;
      color: #d8ded3;

      & > span {
        cursor: pointer;
      }
    }
  }

  .left {
    position: fixed;
    left: 48px;
    top: 60px;
    width: 282px;
    height: calc(100% - 60px);
    background: linear-gradient(
      90deg,
      rgba(25, 47, 61, 0.85),
      rgba(25, 47, 61, 0.1)
    );
    transition: all 1s;
    display: flex;
    flex-direction: column;

    .search-bar {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-bottom: 15px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.2);

      .el-select {
        width: 100%;
      }

      .search-input {
        margin-top: 15px;
      }

      ::v-deep {
        .el-input__inner {
          background-color: rgba(255, 255, 255, 0.2);
          border: 1px solid rgba(255, 255, 255, 0.4);
          border-radius: 0;
          color: #d2e6f0;
        }

        .el-select-dropdown {
          border-color: #4a80a3;

          .el-select-dropdown__empty {
            background-color: #4a80a3;
            color: white;
          }

          .el-select-dropdown__list {
            background-color: #4a80a3;

            .el-select-dropdown__item {
              color: white;
              background-color: #4a80a3;

              &.selected {
                color: white;
              }

              &.hover {
                background-color: #28516c;
              }
            }
          }

          .popper__arrow {
            border-bottom-color: #4a80a3;

            &::after {
              border-bottom-color: #4a80a3;
            }
          }
        }
      }
    }

    .search-result {
      flex: 1;
      overflow-y: hidden;

      &-item {
        padding: 15px 10px;
        display: flex;
        flex-direction: column;
        cursor: pointer;

        &:not(:last-of-type) {
          margin-bottom: 10px;
          border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        }

        .name {
          color: white;
          font-size: 14px;
          font-weight: 500;
        }

        .address {
          display: flex;
          align-items: flex-start;
          margin-top: 10px;

          .img {
            width: 14px;
            height: 14px;
          }

          .label {
            color: #d2e6f0;
            font-size: 12px;
            margin-left: 5px;
          }
        }
      }
    }
  }

  .right-search {
    position: fixed;
    right: 48px;
    top: 60px;
    width: 282px;
    height: calc(100% - 60px);
    background: linear-gradient(
      90deg,
      rgba(25, 47, 61, 0.85),
      rgba(25, 47, 61, 0.1)
    );
    transition: all 1s;
    display: flex;
    flex-direction: column;

    .search-bar {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-bottom: 15px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.2);

      .el-select {
        width: 100%;
      }

      .search-input {
        margin-top: 15px;
      }

      ::v-deep {
        .el-input__inner {
          background-color: rgba(255, 255, 255, 0.2);
          border: 1px solid rgba(255, 255, 255, 0.4);
          border-radius: 0;
          color: #d2e6f0;
        }

        .el-select-dropdown {
          border-color: #4a80a3;

          .el-select-dropdown__empty {
            background-color: #4a80a3;
            color: white;
          }

          .el-select-dropdown__list {
            background-color: #4a80a3;

            .el-select-dropdown__item {
              color: white;
              background-color: #4a80a3;

              &.selected {
                color: white;
              }

              &.hover {
                background-color: #28516c;
              }
            }
          }

          .popper__arrow {
            border-bottom-color: #4a80a3;

            &::after {
              border-bottom-color: #4a80a3;
            }
          }
        }
      }
    }

    .search-result {
      flex: 1;
      overflow-y: hidden;

      &-item {
        padding: 15px 10px;
        display: flex;
        flex-direction: column;
        cursor: pointer;

        &:not(:last-of-type) {
          margin-bottom: 10px;
          border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        }

        .name {
          color: white;
          font-size: 14px;
          font-weight: 500;
        }

        .address {
          display: flex;
          align-items: flex-start;
          margin-top: 10px;

          .img {
            width: 14px;
            height: 14px;
          }

          .label {
            color: #d2e6f0;
            font-size: 12px;
            margin-left: 5px;
          }
        }
      }
    }

    ::v-deep {
      .el-tabs {
        height: 100%;
        margin: 0 16px;
        display: flex;
        flex-direction: column;

        &__nav-wrap::after {
          position: static !important;
        }

        &__active-bar {
          background-color: #00d2ff;
        }

        &__item {
          color: white;
        }

        &__item.is-active {
          color: #00d2ff;
        }

        &__item:hover {
          color: #00d2ff;
        }

        .el-tabs__content {
          flex: 1;

          .el-tab-pane {
            height: 100%;
            display: flex;
            flex-direction: column;

            .el-scrollbar {
              height: 100%;

              &__wrap {
                overflow-x: hidden;
              }
            }
          }
        }
      }
    }
  }

  .right {
    width: 48px;
    height: calc(100vh - 60px);
    position: fixed;
    right: 0;
    top: 60px;
    background: rgba(25, 47, 61, 0.85);
    border-left: 1px solid rgba(255, 255, 255, 0.2);
  }

  .bottom-tab-box {
    position: fixed;
    bottom: 30px;
    left: 50%;
    transform: translateX(-50%);

    .el-scrollbar {
      height: 100%;

      ::v-deep {
        .el-scrollbar__wrap {
          overflow-x: hidden;
          margin-bottom: 0 !important;

          .el-scrollbar__view {
            height: 100%;
          }
        }
      }
    }
  }

  //.bottom-tab-box::-webkit-scrollbar {
  //  width: 0;
  //}

  .shrink {
    height: 53px;
    overflow: hidden;
  }

  .bottom-tab {
    //width: 760px;
    display: flex;
    flex-direction: column-reverse;
    justify-content: center;
  }

  .right-service__wrapper {
    //justify-content: center;
    display: flex;
    flex-direction: row;
    position: relative;
    margin-top: 13px;

    ::v-deep {
      .el-input.is-disabled .el-input__inner {
        cursor: default;
      }

      .el-input__inner {
        background-color: transparent;
        background-image: url('~@/assets/img/select@2x.png');
        background-size: 100% 100%;
        background-repeat: no-repeat;
        color: white;
        border: none;
        text-align: center;
      }
    }
  }

  .right-service {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .service-item {
      position: relative;
      width: 138px;
      height: 35px;
      cursor: pointer;
      color: white;
      font-size: 16px;
      font-weight: 500;
      display: flex;
      align-items: center;
      justify-content: center;
      background: url('~@/assets/img/history-imagery-background.png')
        no-repeat;
      background-size: 100% 100%;

      &:not(:last-of-type) {
        margin-right: 9px;
      }

      &.active-item {
        color: #fefefe;
        font-weight: bold;
        background: url('~@/assets/img/history-imagery-active-background.png')
          no-repeat;
        background-size: 100% 100%;
      }

      &.disabled-item {
        cursor: not-allowed;
      }
    }

    .left-right {
      text-align: center;
      display: inline-block;
      vertical-align: middle;
      font-size: 20px;
      line-height: 25px;
      cursor: pointer;

      &:first-of-type {
        margin-right: 10px;
      }

      &:last-of-type {
        margin-left: 10px;
      }
    }
  }
}
</style>
